package com.tiantianyuegou.activity;

import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.adapter.SearchHistoryAdapter;
import com.tiantianyuegou.database.SearchHistory;
import com.tiantianyuegou.database.dao.SearchHistoryDao;
import com.tiantianyuegou.util.Tools;
import com.tiantianyuegou.view.NoScrollListView;

/**
 * 搜索
 * Created by huyang on 2016/1/7 0007.
 */
public class SearchActivity extends BaseActivity implements View.OnClickListener {
//    http://hjtech.wicp.net:8080/tiantianyuegou-api/product/search?keywords=1&page=1&sort=asc&order=default
    //    http://hjtech.wicp.net:8080/tiantianyuegou-api/product/search?keywords=兰梦得红酒&page=1&sort=1&order=1

    //    /product/search
    private EditText edt_search;
    private TextView tv_cancal;
    private Button btn_remove;//清空历史记录
    private NoScrollListView mListView;
    private SearchHistoryAdapter mAdapter;
    private DataSetObserver observer;
    private Context mContext;
    private final int headCount = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        Tools.changeSystemBar(this);
        initViews();
        addHead();

    }

    @Override
    public void findViewByIds() {
        edt_search = (EditText) findViewById(R.id.edt_search);
        tv_cancal = (TextView) findViewById(R.id.tv_cancel);
        btn_remove = (Button) findViewById(R.id.btn_remove);
        mListView = (NoScrollListView) findViewById(R.id.list);

    }

    @Override
    public void initListener() {
        mContext = this;
        edt_search.setOnClickListener(this);
        tv_cancal.setOnClickListener(this);
        btn_remove.setOnClickListener(this);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                TODO 修改
                SearchHistory history = mAdapter.getItem(position - headCount);
                search(history.content);
            }
        });
        edt_search.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        edt_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String value = edt_search.getText().toString();
                    if (TextUtils.isEmpty(value)){
                        showMsg("请输入你要搜索的商品");
                        return false;
                    }
                    //插入搜索记录
                    SearchHistoryDao.getInstance(mContext).insert(value);
                    hideSoftInput(edt_search.getWindowToken());
                    search(value);
                    return true;
                }
                return false;
            }
        });
        observer = new DataSetObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
                if (mAdapter.isEmpty()) {
                    btn_remove.setVisibility(View.GONE);
                } else {
                    btn_remove.setVisibility(View.VISIBLE);
                }
            }
        };

    }

    //添加搜索记录listview头部
    public void addHead() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.listitem_history_head, mListView, false);
        mListView.addHeaderView(view, null, false);
    }

    @Override
    protected void onDestroy() {
        if (mAdapter != null) {
            mAdapter.unregisterDataSetObserver(observer);
        }
        super.onDestroy();
    }

    @Override
    public void initData() {
        mAdapter = new SearchHistoryAdapter(mContext);
        mAdapter.registerDataSetObserver(observer);
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mListView.setAdapter(mAdapter);
            }
        },100);
        mAdapter.addAll(SearchHistoryDao.getInstance(mContext).queryHistory());
    }

    public void search(String keyWord) {
        Intent intent = getIntent();
        String type = intent.getStringExtra("type");
        System.out.println("---------type=" + type);
        if ("CategoryFragment".equals(type)) {
            Intent intent1 = new Intent(mContext, GoodsListActivity.class);
            intent1.putExtra("keyWords", keyWord);
            startActivity(intent1);
        } else if("IndexFragment".equals(type)){
            Intent intent2=new Intent(mContext,GoodsListActivity.class);
            intent2.putExtra("keyWords",keyWord);
            System.out.println("---------------"+keyWord+"--------------");
            startActivity(intent2);
        }
        else {
            Intent result = new Intent();
            result.putExtra("keyWords", keyWord);
            this.setResult(RESULT_OK, result);



        }
        finish();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel:
                finish();
                break;
            case R.id.btn_remove:
                SearchHistoryDao.getInstance(mContext).delete();
                mAdapter.clear();
                break;
            default:
                break;
        }

    }
}
